package cat.joronya.supermanager.market;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import cat.joronya.supermanager.DatabaseHelper;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.Supermanager.Market;
import cat.joronya.supermanager.Supermanager.PlayerList;

/**
 * Provides access to a database of players, the market place.
 */
public class MarketProvider extends ContentProvider 
{
	// pel Log
	@SuppressWarnings("unused")
	private static final String TAG = "supermanager";
	
	public static final int MARKET_PLAYERS = 1;
	public static final int MARKET_PLAYER_ID = 2;
	public static final int PLAYER_LISTS = 3;
	public static final int PLAYER_LIST_ID = 4;
	
	public static final UriMatcher uriMatcher;
	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(Supermanager.Market.AUTHORITY, "market", MARKET_PLAYERS);
		uriMatcher.addURI(Supermanager.Market.AUTHORITY, "market/#", MARKET_PLAYER_ID);
		uriMatcher.addURI(Supermanager.PlayerList.AUTHORITY, "playerlist", PLAYER_LISTS);
		uriMatcher.addURI(Supermanager.PlayerList.AUTHORITY, "playerlist/#", PLAYER_LIST_ID);
	}
	
    private DatabaseHelper mOpenHelper;
    
    @Override
    public boolean onCreate() {
        mOpenHelper = new DatabaseHelper(getContext());
        return true;
    }
    
	@Override
	public int delete(Uri uri, String where, String[] whereArgs) 
	{
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (uriMatcher.match(uri)) {
		case MARKET_PLAYERS:
			count = db.delete(DatabaseHelper.MARKET_TABLE_NAME, where, whereArgs);
			getContext().getContentResolver().notifyChange(uri, null);
			break;

		case MARKET_PLAYER_ID:
			String id = uri.getPathSegments().get(1);
			count = db.delete(DatabaseHelper.MARKET_TABLE_NAME, Market._ID + "=" + id
					+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
			getContext().getContentResolver().notifyChange(uri, null);
			break;
		
		case PLAYER_LISTS:
			count = db.delete(DatabaseHelper.PLAYERS_LISTS_TABLE_NAME, where, whereArgs);
			getContext().getContentResolver().notifyChange(Supermanager.Market.CONTENT_URI, null);
			break;
			
		case PLAYER_LIST_ID:
			String id2 = uri.getPathSegments().get(1);
			count = db.delete(DatabaseHelper.PLAYERS_LISTS_TABLE_NAME, PlayerList._ID + "=" + id2
					+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
			getContext().getContentResolver().notifyChange(Supermanager.Market.CONTENT_URI, null);
			break;

		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		
		return count;
	}

	@Override
	public String getType(Uri uri) 
	{
		switch (uriMatcher.match(uri)) {
        case MARKET_PLAYERS:
            return Supermanager.Market.CONTENT_TYPE;

        case MARKET_PLAYER_ID:
            return Supermanager.Market.CONTENT_ITEM_TYPE;
            
        case PLAYER_LISTS:
        	return Supermanager.PlayerList.CONTENT_TYPE;
        	
        case PLAYER_LIST_ID:
        	return Supermanager.PlayerList.CONTENT_ITEM_TYPE;

        default:
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
	}

	@Override
	public Uri insert(Uri uri, ContentValues initialValues) 
	{
		if( uriMatcher.match(uri) == MARKET_PLAYERS )
		{
			ContentValues values;
			if (initialValues != null) {
				values = new ContentValues(initialValues);
			} else {
				values = new ContentValues();
			}

			Long now = Long.valueOf(System.currentTimeMillis());

			// afegim el modified si no el tenim als values
			if (values.containsKey(Supermanager.Market.MODIFIED_DATE) == false) {
				values.put(Supermanager.Market.MODIFIED_DATE, now);
			}

			SQLiteDatabase db = mOpenHelper.getWritableDatabase();
			long rowId = db.insert(DatabaseHelper.MARKET_TABLE_NAME, "", values);
			if (rowId > 0) {
				Uri plUri = ContentUris.withAppendedId(Supermanager.Market.CONTENT_URI, rowId);
				getContext().getContentResolver().notifyChange(plUri, null);
				return plUri;
			}
			throw new SQLException("Failed to insert row into " + uri);
		}
		else if(uriMatcher.match(uri) == PLAYER_LISTS)
		{
			ContentValues values;
			if (initialValues != null) {
				values = new ContentValues(initialValues);
			} else {
				values = new ContentValues();
			}

			Long now = Long.valueOf(System.currentTimeMillis());

			// afegim el modified si no el tenim als values
			if (values.containsKey(Supermanager.PlayerList.MODIFIED_DATE) == false) {
				values.put(Supermanager.PlayerList.MODIFIED_DATE, now);
			}

			SQLiteDatabase db = mOpenHelper.getWritableDatabase();
			long rowId = db.insert(DatabaseHelper.PLAYERS_LISTS_TABLE_NAME, "", values);
			if (rowId > 0) {
				// notifiquem al market pq recarregui rows
				getContext().getContentResolver().notifyChange(Supermanager.Market.CONTENT_URI, null);

				// retornem uri d'element insertat
				Uri plUri = ContentUris.withAppendedId(Supermanager.PlayerList.CONTENT_URI, rowId);
				return plUri;
			}
			throw new SQLException("Failed to insert row into " + uri);
		}
		// Validate the requested uri
		else
		{
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) 
	{
		if( uriMatcher.match(uri) == MARKET_PLAYERS )
			return queryMarket(uri, projection, selection, selectionArgs, sortOrder);
		else if ( uriMatcher.match(uri) == PLAYER_LISTS )
			return queryPlayerLists(uri, projection, selection, selectionArgs, sortOrder);
		
		return (Cursor)null;
	}
	
	/**
	 * Query table market with left join over player_lists.
	 * TODO: distinct when a player can be on two lists and its not filtered by list. 
	 */
	public Cursor queryMarket(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) 
	{
		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		sqlBuilder.setTables(DatabaseHelper.MARKET_TABLE_NAME+" m "+
			" LEFT JOIN "+DatabaseHelper.PLAYERS_LISTS_TABLE_NAME+" l "+
			" ON (m."+Supermanager.Market.CODI_PLAYER+"=l."+Supermanager.PlayerList.CODI_PLAYER+")");

		// recuperant un jugador concreta
		if( uriMatcher.match(uri) == MARKET_PLAYER_ID )
			sqlBuilder.appendWhere("m."+Market._ID + " = " + uri.getPathSegments().get(1));                

		// If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = Market.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }
        
        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        
        Cursor c = sqlBuilder.query(
			db, 
			projection, 
			selection, 
			selectionArgs, 
			null, 
			null, 
			orderBy);

		// register to watch a content URI for changes
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}
	
	/**
	 * Query table player_lists.
	 */
	public Cursor queryPlayerLists(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) 
	{
		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		sqlBuilder.setTables(DatabaseHelper.PLAYERS_LISTS_TABLE_NAME);
		sqlBuilder.setDistinct(true);

		// If no sort order is specified use the default
        String orderBy;
        if (TextUtils.isEmpty(sortOrder)) {
            orderBy = PlayerList.DEFAULT_SORT_ORDER;
        } else {
            orderBy = sortOrder;
        }
        
        // Get the database and run the query
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        
        Cursor c = sqlBuilder.query(
			db, 
			projection, 
			selection, 
			selectionArgs, 
			null, 
			null, 
			orderBy);

		// register to watch a content URI for changes
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) 
	{
		SQLiteDatabase db = mOpenHelper.getWritableDatabase();
		int count;
		switch (uriMatcher.match(uri)) {
		case MARKET_PLAYERS:
			count = db.update(DatabaseHelper.MARKET_TABLE_NAME, values, where, whereArgs);
			getContext().getContentResolver().notifyChange(uri, null);
			break;

		case MARKET_PLAYER_ID:
			String id = uri.getPathSegments().get(1);
			count = db.update(DatabaseHelper.MARKET_TABLE_NAME, values, Market._ID + "=" + id
					+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
			getContext().getContentResolver().notifyChange(uri, null);
			break;
			
		case PLAYER_LISTS:
			count = db.update(DatabaseHelper.PLAYERS_LISTS_TABLE_NAME, values, where, whereArgs);
			getContext().getContentResolver().notifyChange(Supermanager.Market.CONTENT_URI, null);
			break;

		case PLAYER_LIST_ID:
			String id2 = uri.getPathSegments().get(1);
			count = db.update(DatabaseHelper.PLAYERS_LISTS_TABLE_NAME, values, Market._ID + "=" + id2
					+ (!TextUtils.isEmpty(where) ? " AND (" + where + ')' : ""), whereArgs);
			getContext().getContentResolver().notifyChange(Supermanager.Market.CONTENT_URI, null);
			break;
			
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}

		
		return count;
	}

	/**
	 *  recuperem market available days
	 * @param context
	 * @return
	 */
	public Cursor getDays(Context context)
    {
    	SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
    	sqlBuilder.setTables(DatabaseHelper.MARKET_TABLE_NAME);
    	
    	sqlBuilder.setDistinct(true);
    	
    	String[] PROJECTION = new String[]{
				DatabaseHelper.MARKET_TABLE_NAME+"."+Supermanager.Market.DAY			// 0
		};
    	
    	// Get the database and run the query
		mOpenHelper = new DatabaseHelper(context);
        SQLiteDatabase db = mOpenHelper.getReadableDatabase();
        
        Cursor c = sqlBuilder.query(
			db, 
			PROJECTION, 
			null, 
			null, 
			null, 
			null, 
			DatabaseHelper.MARKET_TABLE_NAME+"."+Supermanager.Market.DAY+" ASC ");
        
        return c;
    }

}
